﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace QXBook.Handlers.AjaxHandlers
{
    public class AjaxMappinger
    {
        public static void Mapping<T>(object obj, Func<string, T, string> getParamValue) where T : AjaxMappingAttribute
        {
            Type t = obj.GetType();
            foreach (PropertyInfo pi in t.GetProperties())
            {
                object[] customerAttributes = pi.GetCustomAttributes(typeof(T), false);
                if (customerAttributes.Length == 1)
                {
                    MethodInfo setMethod = pi.GetSetMethod();
                    if (setMethod != null)
                    {
                        T mapping = customerAttributes[0] as T;
                        //参数名称，如果没有指定参数名称，则默认为属性名称
                        string paramName = string.IsNullOrEmpty(mapping.ParamName) ? pi.Name : mapping.ParamName;

                        string paramValue = getParamValue(paramName, mapping);
                        if (paramValue == null)
                        {
                            if (mapping.IsRequired)
                            {
                                throw new ArgumentNullException(string.Format("未提供参数{0}的值", paramName));
                            }
                            else
                            {
                                continue;
                            }
                        }
                        setMethod.Invoke(obj, new object[] { paramValue });
                    }
                    else
                    {
                        throw new Exception(string.Format("未定义数据{0}的set构造器，无法进行赋值。", pi.Name));
                    }
                }
            }
        }
    }
}
